package com.lumlord.service;

import java.util.*;

import com.lumlord.common.annotation.mybatis.Master;
import com.lumlord.common.domain.*;
import com.lumlord.common.log.Log;
import com.lumlord.common.log.LogFactory;
import com.lumlord.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lumlord.common.exception.BusinessException;
import com.lumlord.common.shiro.util.JwtUtils;
import com.lumlord.common.shiro.util.ShiroUtils;
import com.lumlord.common.spring.RequestJsonBody;

/**
 * 用户控制
 *
 * @author gpf
 */

@Service
public class SystemUserService {

    /**
     * 密碼加密
     * @param password
     * @return
     */
    public  String exchangePws(String password){
        return MD5Util.encode(password);
    }

    /**
     * 根据手机号查找用户
     *
     * @param mobile
     * @return
     * @throws BusinessException
     */
    public User selectUserByMobilePhone(String mobile) throws BusinessException {
        if (null == mobile) {
            return null;
        }

        User user = new User();
        user.setMobilePhone(mobile);
        return jdbcTemplateUtils.queryOne(user);
    }

    /**
     * 写入 返回信息
     * @return
     */
    @SuppressWarnings({  "rawtypes" })
    public Map getUserInfo() {
        Map u = ShiroUtils.getUserMap();
        return u;
    }

    /**
     * 设置用户项目 ，组织机构， 角色权限信息
     *
     * @param user
     * @throws BusinessException
     */
    public void putInfo(User user) throws BusinessException {
        user.setActions(getFullMenuTree(user.getPostId()));
    }


    /**
     * 獲取菜單樹
     *
     * @return
     */
    public List<LumlordApi> getFullMenuTree(Integer postId) {
        return getAllMenuTree(postId, requestJsonBody.isApp() ? 1 : 0);
    }


    private List<LumlordApi> transformationTree(List<LumlordApi> apis) {
        List<LumlordApi> apiList = new ArrayList<LumlordApi>();
        Iterator<LumlordApi> it = apis.iterator();
        while (it.hasNext()) {
            LumlordApi api = it.next();
            if (null == api.getParantId() || 1 == api.getParantId()) {
                apiList.add(api);
            }
        }

        for (LumlordApi api : apis) {
            if (null == api.getParantId() || 1 == api.getParantId()) {
                continue;
            } else {
                findTreeParet(apiList, api);
            }
        }
        return apiList;
    }

    /**
     * 递归赋值树，权限数据
     *
     * @param apis
     * @param currentApi
     */
    private void findTreeParet(List<LumlordApi> apis, LumlordApi currentApi) {
        for (LumlordApi api : apis) {
            if (currentApi.getParantId().equals(api.getId())) { //找到 currentApi 的 子级
                api.getActions().add(currentApi);
                break;
            } else if (api.getActions().size() >= 0) { //
                findTreeParet(api.getActions(), currentApi);
            }
        }
    }


    /**
     * 移除 用户 缓存数据
     *
     * @param account
     */
    public void removeCacheUser(String account) {
        String jwtTOKEN = jwtUtils.sign(account);
        jwtUtils.removeCacheUser(jwtTOKEN);
    }

    /**
     * 写入登录信息
     *
     * @throws BusinessException
     */
    @Master
    public void writeLoginInfo(User user) throws BusinessException {
        if (null == user.getLoginTimes()) {
            user.setLoginTimes(1);
        } else {
            user.setLoginTimes(user.getLoginTimes() + 1);
        }

        if (null != user.getTooken()) {
            jwtUtils.removeCacheUser(user.getTooken());
        }
        //设入tooken 记录redis 登录信息
        String jwtTOKEN = jwtUtils.sign(user.getAccount());
        jwtUtils.setTokenRefresh(jwtTOKEN, user.getAccount(), user.getId());
        user.setTooken(jwtTOKEN);

        try {
            user.setIp(accessAddressUtil.getIpAddress(RequestToBean.getRequest()));
        } catch (Exception e) {
            // TODO: handle exception
        }
        //设入 ip
        //设入 最后登录时间
        user.setLastLoginTime(new Date());
        jdbcTemplateUtils.updateById(user);
    }


    /**
     * 获取当前登录用户的权限信息
     *
     * @return
     */
    public List<LumlordApi> getPermission() {
        User user = ShiroUtils.getUser();
        //直接从数据库获取
        if (user == null) {
            return new ArrayList();
        }
        return getFullMenuTree(user.getPostId());
    }

    /**
     * 獲取菜單樹 只显示 业务口所展示 权限
     * @return
     */
    public List<LumlordApi> getFullMenuTree(){
        String sql = " select * from t_action  where PARANT_ID<>'-1' and STATUS=0 order by  (MENU_CODE+0)  asc  ";
        List<LumlordApi> menus = transformationTree(jdbcTemplateUtils.queryList(sql, LumlordApi.class));
        return menus;
    }



    /**
     * 獲取菜單樹
     *
     * @return
     */
    public List<LumlordApi> getAllMenuTree(Integer postId, Integer visit) {
        String sql = "SELECT ta.* from t_action ta right JOIN " +
                "(SELECT * from t_role_permission  where role_id in (SELECT role_id from t_post_role where post_id=? and STATE=0) ) tr " +
                "on ta.id=tr.action_id " +
                "WHERE  ta.STATE=0 and  ta.STATUS=0 and ta.VISIT=? " +
                "ORDER BY ta.id asc";
     return transformationTree(jdbcTemplateUtils.queryList(sql, LumlordApi.class, postId, visit));
    }

    /**
     * 职位是否有效
     * @return true 无效 false 有效
     */
    public boolean postValid(Integer postId){
        return null == jdbcTemplateUtils.queryOne("select * from t_post where STATE=0 and POST_ID=?",Map.class,postId);
    }


    /**
     * 根据用户名，手机号查找用户
     *
     * @param accountMobile
     * @return
     */
    public User selectUserByMobileAccount(String accountMobile) {
        if (null == accountMobile) {
            return null;
        }
        String sql = "SELECT * FROM t_user  WHERE ACCOUNT=? or MOBILE_PHONE=?  order by id desc ";
        List<User> users = jdbcTemplateUtils.queryList(sql, User.class, accountMobile, accountMobile);
        User user = null;
        for (User u : users) {
            if (u.getStatus() != 1 && u.getState() != 1) {
                user = u; //可用账号
            }
        }

        if (user == null && users.size() > 0) {
            user = users.get(0);
        }

        if (null != user) {
            return user;
        } else {
            return null;
        }
    }

    @Autowired
    private RequestJsonBody requestJsonBody;
    @Autowired
    private AccessAddressUtil accessAddressUtil;
    @Autowired
    private JdbcTemplateUtils jdbcTemplateUtils;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private CommonService commonService;

    public Log log = new LogFactory(getClass());
}
